package com.tarena.lbs.marketing.web.filters;

import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.marketing.web.utils.AuthenticationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Slf4j
public class AuthenticationFilter implements Filter {
    private static final String AUTHORIZATION="Authorization";
    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //添加请求头 Authorization jwt的解析
        UserPrinciple userPrinciple=null;
        if (servletRequest instanceof HttpServletRequest){
            //是http请求
            HttpServletRequest request=(HttpServletRequest)servletRequest;
            //拿到请求头
            String jwt = request.getHeader(AUTHORIZATION);
            if(jwt!=null&&jwt.length()>0){
                //我们确定jwt有值
                try{
                    userPrinciple=jwtEncoder.getLoginFromToken(jwt,UserPrinciple.class);
                }catch (Exception e){
                    log.error("携带的jwt解析失败",e);
                }
            }
        }
        //如何将过滤器解析的userPrinciple传递到下游代码中
        AuthenticationContextUtils.set(userPrinciple);
        Thread thread = Thread.currentThread();//拿到当前方法执行的线程对象
        log.info("当前过滤器方法线程id:{}",thread.getId());
        log.info("当前过滤器方法线程执行对象:{}",thread);
        //1.可以将userPrinciple 放到request的域中
        filterChain.doFilter(servletRequest,servletResponse);
        //当前请求即将返回响应 需要使用工具 将ThreadLocal中的当前线程数据清空
        AuthenticationContextUtils.clear();
    }
}
